const http = require('./api.js');
import {
    request
} from '../libs/wx-promise-request';
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function login() {

    return new Promise((resolve, reject) => {
        wx.login({
            success: res => {
                // console.log("code " + res.code)
                let code = res.code
                //获取用户信息
                wx.getUserInfo({
                    withCredentials: true,
                    success: res => {
                        wx.setStorageSync('first', false)
                        // console.log(res)
                        let url = http.api.login;
                        myHttpss({
                            url: url,
                            method: 'POST',
                            data: {
                                'code': code,
                                'encryptedData': res.encryptedData,
                                'iv': res.iv,
                            }
                        }).then(res => {
                            //获取用户信息本地存储下
                            // console.log(res.data.content)
                            wx.setStorageSync('userId', res.data.content.id)
                            wx.setStorageSync('userInfo', res.data.content)

                            let token = res.data.token;
                            wx.setStorageSync(
                                'Authorization', 'Bearer ' + token
                            )
                            resolve(res)
                        })
                    }, fail: function (res) {
                        wx.setStorageSync(
                            'no_login', 'yes'
                        )
                    }
                })

            },
            fail: function (res) {
            }
        })
    })
}

const myHttpss = object => request({
    ...object,

    header: {
        ...object.header,
        'Authorization': wx.getStorageSync('Authorization'),
        'Content-Type': 'application/json;charset=utf-8' 
    }
}).then(function (res) {
    if (res.statusCode == 200) {
        return res.data
    } else if (res.statusCode == 401) {
        wx.showModal({
            title: '抱歉',
            content: '服务器开小差了',
            confirmText: '点击重试',
            showCancel: false,
            success: function (res) {
                if (res.confirm) {
                    login().then((res) => {
                        wx.switchTab({
                            url: '/pages/index/index',
                        })
                    })
                }
            }
        })
    } else {
        // console.log('请求失败')
        wx.showLoading({
            title: '服务器开小差...',
        })
        setTimeout(() => {
            wx.hideLoading()
        }, 500)
    }
})
const myHttpHeader = object => request({
    ...object,
    header: {
        ...object.header,
        'Authorization': wx.getStorageSync('Authorization'),
        'Content-Type': 'application/json;charset=utf-8'
    }
})
module.exports = {
    formatTime: formatTime,
    myHttpss: myHttpss,
}